import axios from 'axios'
import router from '../router'
import { Toast } from 'vant'

/**
 * 提示函数
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = (msg, time) => {
  Toast({
    message: msg,
    duration: time,
    forbidClick: true
  })
}

/**
 * 跳转首页
 */
const toLogin = () => {
  sessionStorage.removeItem('token')
  router.replace({
    name: 'Login'
  })
}

/**
 * 请求失败统一处理
 * @param {number} status 请求失败状态码
 */
const errorHandle = (status, other) => {
  switch (status) {
    // 登陆过期，跳转登陆
    case 401:
      Toast.fail('登陆失效')
      toLogin()
      break
    case 404:
      Toast.fail('请求资源不存在')
      break
    case 500:
      Toast('与服务器失去连接~')
      break
    default:
      console.log(other)
  }
}

// 创建axios实例
var instance = axios.create({ timeout: 1000 * 50 })
// 请求头部信息为post请求设置
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// 请求拦截
instance.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    token && (config.headers.token = token)
    return config
  },
  error => Promise.error(error)
)
// 响应拦截
instance.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.code === 0) {
        tip(response.data.msg, 2000)
        return Promise.resolve(response.data)
      } else {
        Toast.clear()
        return Promise.resolve(response.data)
      }
    } else {
      return Promise.reject(response.data)
    }
  },
  err => {
    if (err.message.includes('timeout')) {
      console.log('错误回调', err)
      tip('网络超时', 1000)
      return Promise.reject(err)
    }
    const { response } = err
    if (response) {
      errorHandle(response.status, response.data.message)
      return Promise.reject(response)
    } else {
      if (!window.navigator.onLine) {
        tip('网络状态不佳，请稍后重试', 1000)
      } else {
        return Promise.reject(err)
      }
    }
  }
)

export default instance
